package com.hd.trans.ui.activity.auxiliary;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;

import com.hd.trans.R;

public class MyHomePopWindow {
    private Context context;

    private PopupWindow pop;
    private int viewHeight;
    private int windowHeight;
    private int popupHeight;
    private int mPosition;

    public MyHomePopWindow(Context context) {
        this.context = context;
    }

    public void showPopup(View view, int position, CallbackListener listener) {
        mPosition = position;
        View v = LayoutInflater.from(context).inflate(R.layout.layout_menu_text_record, null);
        if (pop == null) {
            pop = new PopupWindow(context);
            pop.setContentView(v);
            pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            pop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            pop.setFocusable(true);
            pop.setOutsideTouchable(true);
            //测量popupwindow高度
            v.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            popupHeight = v.getMeasuredHeight();  //获取测量后的高度
            //顺便也测一下依附控件高度
            view.findViewById(R.id.view_null).measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            viewHeight = view.findViewById(R.id.view_null).getMeasuredHeight();
        }

        v.findViewById(R.id.menu_copy).setOnClickListener(new View.OnClickListener() {//复制
            @Override
            public void onClick(View v) {
                if (listener != null)
                    listener.copy(view, mPosition);
                pop.dismiss();
            }
        });
        v.findViewById(R.id.menu_delete).setOnClickListener(new View.OnClickListener() {//删除
            @Override
            public void onClick(View v) {
                if (listener != null)
                    listener.delete(view, mPosition);
                pop.dismiss();
            }
        });

        //创建长度为2的数组，分别记录指定view在屏幕的x 和 y轴
        int[] location = new int[2];
        // 获得指定view在屏幕的位置
        view.findViewById(R.id.view_null).getLocationOnScreen(location);

        //判断view在屏幕Y轴离底部不够一个pop的高度
        if (windowHeight - popupHeight - viewHeight > location[1]) {
            //如果够就显示在底部
            pop.showAsDropDown(view.findViewById(R.id.view_null));
        } else {
            pop.showAtLocation(view.findViewById(R.id.view_null), 0, location[0], location[1] - popupHeight);
        }

    }

    public interface CallbackListener{
        void copy(View view, int position);
        void delete(View view, int position);
    }
}
